package com.jintoufs.web.action.ad;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.common.util.JhjResponseUtil;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.domain.activiti.Activiti;
import com.jintoufs.domain.ad.Ad;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.ad.AdService;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jintoufs.util.ResponseUtil.writeInfo;

/**
 * 广告管理
 * Created by xufei on 2017/12/20.
 */
@Controller
@Scope("prototype")
@RequestMapping("/ad")
public class AdAction extends SupportAction {

    @Resource
    private AdService adService;


    /**
     *广告查询
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public String list() throws IOException {
        return "ad/list";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Ad> list = adService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }


    /**
     * input.do?id= 进入广告编辑与新增页面 <br>*
     * @param id    活动Id
     * @param model
     * @return
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(Integer id, Model model) {
        Map map = new HashMap();
        // 是否为编辑保存
        Boolean isEdit = false;

        if (id != null) {
            // 修改
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", id);
            List<Map<String,Object>> list = adService.queryByParams(params);
            if (list != null && list.size() > 0) {
                map = list.get(0);
            }
            isEdit = true;
        } else {
            // 新增
        }

        model.addAttribute("isEdit", isEdit);
        model.addAttribute("entity", map);
        return "ad/input";
    }

    @RequestMapping(value = "add")
    @SystemControllerLog(description = "新增广告")
    public void save(Ad ad, HttpServletResponse response) throws ParseException {
        String error = null;
        if(ad.getName() == null && "".equals(ad.getName())){
            error = "广告名称不能为空！";
        }

//        DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time=format.format(new Date());
//        ad.setEndTime(format.parse(time));
        Map<String, Object> result = adService.save(ad);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }




    @RequestMapping("delete")
    @SystemControllerLog(description = "删除广告")
    public void delete(HttpServletResponse response, Integer[] id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            for (Integer _id:id){
                adService.delete(_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DataIntegrityViolationException) {
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("广告还在使用中，删除失败！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    /**
     * 获取详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "查看广告详细信息")
    public String getDetail(Integer id, Model model) {
        Ad result = new Ad();
        if (id != null && id != 0) {
            result = adService.getById(id);
        }
        model.addAttribute("entity", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "广告详细信息");
        return "ad/detail";
    }

    @RequestMapping("/red/{id}")
    public String redImg(@PathVariable Integer id, Model model, HttpServletRequest request){
        try {
            Ad ad = adService.getById(id);
            model.addAttribute("url",ad.getImageUrl());
            return "/images/display";
        }catch (Exception e){
            e.printStackTrace();
            return request.getHeader("Referer");
        }
    }

}
